$(function () {
    formObj.init();
});

var formObj = new function () {
    'use strict';
    return {
        dataGrid: null,
        form: null,
        type: null,
        iId: 0,
        num: 0,
        params: {
            schoolId: null,
            sExtra: null,
        },
        init: function () {
            this.iId = xhTool.getQuery('iId');
            this.form = new xhForm($('#xh_form'));
            this.form.parse().bindRequired($('#bt_modal_confirm,parent.document'));

            var path = [];
            var con = [];
            var $this = this;
            var selectYear = $('#selectYear').val();
            $('.table'+selectYear).show();
            $.each(users, function (id, value) {
                if (value.iState != 1 && value.iState != 2){
                    var data =JSON.parse(value.sPayVoucherUrl);
                    var uid = value.iUserId;
                    var year = value.iChargeYear;
                    if (Array.isArray(data)) {
                        path[id] = data;
                        con[id] = [];
                        $.each(data, function (k, v) {
                            var imgUrl = '<input name = "payVoucher[' + uid + ']['+year+'][]" class="file' + id + '" type="hidden" value="' + v + '" />';
                            $('#payVoucher' + uid+year).before(imgUrl);
                            var num = v.lastIndexOf('.');
                            var nameNum = v.lastIndexOf('/');
                            var name = v.slice(nameNum + 1)
                            var str = v.slice(num + 1).toLowerCase();
                            var text = ['txt'];
                            var image = ['jpg', 'jpeg', 'png', 'gif', 'bpm'];
                            var office = ['doc', 'xls', 'ppt', 'xlsx', 'docx'];
                            var pdf = ['pdf'];
                            if (text.indexOf(str) != -1) {
                                con[id].push({
                                    type: "text",
                                    caption: name,
                                    url: baseUrl + "school/deleteFile",
                                    key: k + 1
                                });
                            }
                            if (image.indexOf(str) != -1) {
                                con[id].push({
                                    type: "image",
                                    caption: name,
                                    url: baseUrl + "school/deleteFile",
                                    key: k + 1
                                });
                            }
                            if (office.indexOf(str) != -1) {
                                con[id].push({
                                    type: "other",
                                    caption: name,
                                    url: baseUrl + "school/deleteFile",
                                    key: k + 1
                                });
                            }
                            if (pdf.indexOf(str) != -1) {
                                con[id].push({
                                    type: "pdf",
                                    caption: name,
                                    url: baseUrl + "school/deleteFile",
                                    key: k + 1
                                });
                            }
                        });
                        $this.funObj().uploadFile(uid,year,path[id],con[id]);
                    }else{
                        $this.funObj().uploadFile(uid,year,path[id],con[id]);
                    }
                } else {
                    var contentStr = '无附件';
                    if (!value.fileInfo){
                        $('#fileList'+user.iUserId).empty().append('无附件');
                    }else {
                        if (value.fileInfo.sImages){
                            contentStr = '<table style="width: 100%;"><tr><td>附件：</td></tr><tr><td>'+xhShowFile.showImage({fileArr : value.fileInfo.sImages, id: value.fileInfo.ids,showDelete:false})+'</td></tr>' +
                                '</table>';
                        }
                        $('#fileList'+value.iUserId+value.iChargeYear).empty().append(contentStr);
                        $('.images').viewer();
                    }
                }
            });
            this.listener();
        },
        listener: function () {
            var $this = this;
            // 保存
            $('#bt_form_keep').click(function () {
                $this.funObj().saveApply(schoolName,1);
            });
            // 提交申请单
            $('#bt_form_add').click(function () {
                $this.funObj().saveApply(schoolName,2);
            });

            $('#bt_form_close').click(function () {
                window.top.xhTop.closeActiveTab();
            });
            $('.tab-close').click(function () {
                return false;
            });
            $('#selectYear').change(function () {
                $('.inputFiles').fileinput('refresh');
                var selectYear = $('#selectYear').val();
                for (var x in chargeYear)
                {
                    $('.table'+x).hide();
                }
                $('.table'+selectYear).show();
            });
        },
        funObj: function () {
            var $this = this;
            return {
                //保存按钮处理事件
                saveApply: function (schoolName,type) {
                    var selectYear = $('#selectYear').val();
                    var ifSucess = 1;
                    $.each(users, function (id, value) {
                        if(value.iChargeYear == selectYear) {
                            if (value.iState !=1 && value.iState !=2) {
                                var num =  $('input[name="payVoucher[' + value.iUserId + ']['+selectYear+'][]"]').length;
                                if (num < 2) {
                                    window.top.xhTop.showError(value.sUserName+'缴费凭证为空！');
                                    ifSucess = 0;
                                    return false;
                                }
                            }
                        }
                    });
                    if (ifSucess==1){
                        var tabName = '学校设置-'+schoolName+'-学生管理';
                        $this.form.submit('school/savePayVoucher', {type:type}, function (res) {
                            if (xhExtra.checkError(res)) {
                                return false;
                            } else {
                                window.top.xhTop.showSuccess(res.msg);
                                window.top.xhTop.getFrameByName(tabName).obj.dataGrid.reload();
                                window.top.xhTop.closeActiveTab();
                            }

                        }, {check: false});
                    }
                },
                uploadFile: function (eleid,year,path, con) {
                    $("#payVoucher" + eleid + year).fileinput('destroy').fileinput({
                        language: 'zh', //设置语言
                        uploadUrl: baseUrl + 'school/uploadFile',
                        allowedFileExtensions: ['jpg', 'jpeg', 'png', 'gif', 'bpm'],//接收的文件后缀
                        showRemove:false,
                        uploadAsync:true,
                        // showUpload:false,
                        //编辑已成功上传过的图片
                        overwriteInitial: false,
                        initialPreviewAsData: true,
                        initialPreviewFileType: 'image',
                        initialPreview: path, //要显示的图片的路径
                        initialPreviewConfig: con,
                        initialPreviewShowDelete: true,
                        //
                        previewSettings: 600,
                        allowedPreviewTypes: ['image'],
                        // uploadAsync: true, //默认异步上传
                        showUpload: true, //是否显示上传按钮
                        showCaption: false,//是否显示标题
                        dropZoneEnabled: false,
                        browseClass: "btn btn-primary", //按钮样式
                        maxFileSize: 50000,
                        maxFileCount: 10, //表示允许同时上传的最大文件个数
                        enctype: 'multipart/form-data',
                        validateInitialCount: true,
                        height: 200,
                        previewFileIcon: "<i class='glyphicon glyphicon-king'></i>",
                        msgFilesTooMany: "选择上传的文件数量({n}) 超过允许的最大数值{m}！"
                    });

                    $("#payVoucher" + eleid + year).on("fileuploaded", function (event, data, previewId, index) {
                        var url = data.response.msg.url;
                        var fileUrl = '<input name = "payVoucher[' + eleid + ']['+year+'][]" class="file' + eleid + '" type="hidden" value="' + url + '" />';
                        $('#payVoucher' + eleid+year).before(fileUrl);

                    });
                    //
                    $("#payVoucher" + eleid+ year).on("filesuccessremove", function (event, id) {
                        var num = id.lastIndexOf('-');
                        var str = id.slice(num + 1);
                        $('input[name="payVoucher[' + eleid + ']['+year+'][]"]').eq(str).remove();
                    });
                    $("#payVoucher" + eleid + year).on("filedeleted", function (event, key, jqXHR, data) {
                        $('input[name="payVoucher[' + eleid + ']['+year+'][]"]').eq(key - 1).remove();
                    });

                },
            }
        }
    }
};